package com.ssh.dao.impl;

import com.ssh.dao.BzdmDao;
import com.ssh.dao.UserDao;
import com.ssh.entity.Bzdm;
import com.ssh.entity.Person;
import com.ssh.entity.User;
import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.io.Serializable;
import java.util.List;

@Repository
@Transactional
public class UserDaoImpl implements UserDao {
    @Autowired
    private SessionFactory sessionFactory;
    public void setSessionFactory(SessionFactory sessionFactory){
        this.sessionFactory = sessionFactory;
    }

    @Override
    public List<User> getAllUser(String username,String yhbm) {
        String hql = "from User " ;
        if (!StringUtils.isEmpty(username)) {
            hql = hql + " where yhxm like concat('%',?,'%') or yhid like concat('%',?,'%')";
        }
        Query query = sessionFactory.getCurrentSession().createQuery(hql);
        if (!StringUtils.isEmpty(username)) {
            query.setString(0, username);
            query.setString(1, username);
        }
        return query.list();

    }

    @Override
    public User get(String yhid) {
        String hql = "from User u where u.yhid=?";
        Query query = sessionFactory.getCurrentSession().createQuery(hql);
        query.setString(0, yhid);
        return (User)query.uniqueResult();
    }

    @Override
    public void save(User user) {
//        String hql = "insert \n" +
//                "    into\n" +
//                "        T_USER\n" +
//                "        (CSRQ, DJSJ, DWDM, PXH, SFJY, YHBM, YHID, YHKL, YHXB, YHXM, YHDM) \n" +
//                "    values\n" +
//                "        (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
//        Query query = sessionFactory.getCurrentSession().createQuery(hql);
//        query.setString(0, user.getCsrq());
//        query.setString(1, user.getDjsj());
//        query.setString(2, user.getDwdm());
//        query.setInteger(3, user.getPxh());
//        query.setInteger(4, user.getSfjy());
//        query.setString(5, user.getYhbm());
//        query.setString(6, user.getYhid());
//        query.setString(7, user.getYhkl());
//        query.setString(8, user.getYhxb());
//        query.setString(9, user.getYhxm());
//        query.setString(10, user.getYhdm());
//        return (query.executeUpdate() > 0);
        sessionFactory.getCurrentSession().saveOrUpdate(user);
    }

    @Override
    public boolean delete(String yhid) {
        String hql = "delete User u where u.yhid = ?";
        Query query = sessionFactory.getCurrentSession().createQuery(hql);
        query.setString(0, yhid);
        return (query.executeUpdate() > 0);
    }
}
